﻿using Serilog;
using Serilog.Events;
using Serilog.Filters;

namespace Huioo.Learning.Serilog.ConsoleApp1
{
    /// <summary>
    /// 示例，配置
    /// </summary>
    internal class Program
    {
        static void Main(string[] args)
        {
            //临时记录器
            using var logger = new LoggerConfiguration()
                .WriteTo.Console()
                .CreateLogger();
            logger.Information("Hello, Serilog!");

            //全局、静态的记录器
            Log.Logger = new LoggerConfiguration()
                //记录器的日志事件级别，最低级别
                .MinimumLevel.Debug()
                //增强器
                .Enrich.With(new ThreadIdEnricher())
                .Enrich.WithProperty("Version", "1.0.0")
                //基于控制台的接收器
                .WriteTo.Console(
                    //使用输出模板（outputTemplate 参数）来控制格式。
                    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} " +
                    "[{Level:w3}] ({ThreadId}) " +
                    "{Message:lj}{NewLine}" +
                    "{Properties:j}{NewLine}" +
                    "{Exception}"
                )
                //基于文本的接收器
                .WriteTo.File("logs/myapp.txt",
                    // 接收器的日志事件级别，最低级别
                    restrictedToMinimumLevel: LogEventLevel.Warning,
                    rollingInterval: RollingInterval.Day)
                //子记录器
                .WriteTo.Logger(lc => lc
                    //过滤器
                    .Filter.ByIncludingOnly(Matching.WithProperty<int>("Count", p => 100 > p && p > 10))
                    .WriteTo.File("myapp.log1.txt")
                )
                //过滤器
                .Filter.ByExcluding(Matching.WithProperty<int>("Count", p => p < 10))
                .CreateLogger();

            Log.Verbose(    "Hello, world!"); // no show in the console
            Log.Debug(      "Hello, world!");
            Log.Information("Hello, world!");
            int a = 10, b = 0;
            try
            {
                Log.Debug(      "Dividing {A} by {B}", a, b);
                Log.Warning(    "Dividing by {B}, if zero will wrong!", b);
                Console.WriteLine(a / b); // can't execute
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Something went wrong");
                if (ex is DivideByZeroException)
                    Log.Fatal(ex, "Divide By Zero Exception");
            }
            finally
            {
                Log.CloseAndFlush();
                //await Log.CloseAndFlushAsync();
            }
        }
    }
}
